package api.connection;

import api.Configuration;
import benchmarks.tpch.mysql.ScriptRunner;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionMySQL implements DBConnection<Connection> {
    private Configuration config;

    public ConnectionMySQL(Configuration config) {
        this.config = config;
    }

    public Connection makeConnection() {
        Connection connect = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connect = DriverManager
                    .getConnection("jdbc:mysql://"+config.getDb_connection()+"/tpch?"
                            + "user="+config.getDb_username()+"&password="+config.getDb_password()+"&useSSL=true");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connect;
    }

    private static class TestConnectMySQL {
        public static void main(String[] args) throws IOException, SQLException {
            InputStream configStream = ConnectionMySQL.class.getClassLoader().getResourceAsStream("config.json");
            Configuration config = new Gson().fromJson(new InputStreamReader(configStream), Configuration.class);
            DBConnection DBconnect = new ConnectionMySQL(config);

            Connection connect  = (Connection) DBconnect.makeConnection();
            ScriptRunner scriptRunner = new ScriptRunner(connect, false, true);
            scriptRunner.runScript(new BufferedReader(new InputStreamReader(
                    ConnectionMySQL.class.getClassLoader().getResourceAsStream("tpch-mysql-ddl.sql"))));
        }
    }
}
